package wsserver

import (
	"fmt"
	"net/http"
	"time"

	"chat.com/server/wsserver/connection"
	"github.com/gorilla/websocket"
	"github.com/spf13/viper"
)

// 启动程序
func StartWebSocket() {
	serverIp := viper.GetString("")
	webSocketPort := viper.GetString("app.webSocketPort")
	rpcPort := viper.GetString("app.rpcPort")
	serverPort := rpcPort

	http.HandleFunc("/ws", wsPage)

	// 添加处理程序
	go connection.ConnectionManagerInstance.Start()
	fmt.Println("WebSocket 启动程序成功", serverIp, serverPort)

	http.ListenAndServe(":"+webSocketPort, nil)
}

// 建立webSocket连接
func wsPage(w http.ResponseWriter, req *http.Request) {

	// 升级协议
	conn, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {
		fmt.Println("升级协议", "ua:", r.Header["User-Agent"], "referer:", r.Header["Referer"])
		return true
	}}).Upgrade(w, req, nil)

	if err != nil {
		http.NotFound(w, req)
		return
	}

	// 建立webSocket连接
	fmt.Println("webSocket 建立连接:", conn.RemoteAddr().String())

	currentTime := uint64(time.Now().Unix())
	client := connection.NewConnection(conn.RemoteAddr().String(), conn, currentTime, 0)

	go client.Read()
	go client.Write()

	// 用户建立webSocket连接事件通知
	connection.ConnectionManagerInstance.RegisterVisitorCh <- client
}
